单击sproutcore中的按钮添加textfield



如何在sproutcore中单击同一视图中的按钮,在视图中添加更多文本字段?

我有一个带有特定数量文本字段的滑动窗格。单击一个按钮,我需要在同一视图中添加更多的文本字段。

或者,

我应该能够从选择按钮视图中选择数字,并在同一视图中显示这些数字的文本字段。

为此,我建议使用SC.ListView。

您应该有一个SC.ArrayController,其内容是一个包含表示每个文本字段的对象的数组。这可能像这样简单:

MyApp.myController = SC.ArrayController.create({
  content: [
    SC.Object.create({ someProperty: "Text field value 1" }),
    SC.Object.create({ someProperty: "Text field value 2" }),
    SC.Object.create({ someProperty: "Text field value 3" })
  ]
});

接下来,您将创建SC.ListView并将其内容绑定到控制器,然后创建exampleView,其内容绑定至对象的someProperty属性:

MyApp.MyView = SC.View.extend({
  childViews: 'scrollView addButtonView'.w(),
  scrollView: SC.ScrollView.extend({
    layout: { top: 0, left: 0, right: 0, bottom: 50 },
    contentView: SC.ListView.extend({
      contentBinding: 'MyApp.myController.arrangedObjects',
      rowHeight: 40,
      exampleView: SC.View.extend({
        childViews: 'textFieldView'.w(),
        textFieldView: SC.TextFieldView.extend({
          // Add a little margin so it looks nice
          layout: { left: 5, top: 5, right: 5, bottom: 5 },
          valueBinding: 'parentView.content.someProperty'
        })
      })
    })
  }),
  addButtonView: SC.ButtonView.extend({
    layout: { centerX: 0, bottom: 10, width: 125, height: 24 },
    title: "Add Text Field",
    // NOTE: The following really should be handled by a statechart
    // action; I have done it inline for simplicity.
    action: function() {
      MyApp.myController.pushObject(SC.Object.create({ value: "New Field" }));
    }
  })
});

现在,当您单击"添加文本字段"按钮时,它将向控制器阵列添加一个新对象,控制器阵列将自动使用新对象重新渲染列表视图,从而使用新文本字段。

注意事项:

  1. 这将使用SC.ScrollView和SC.ListView,您几乎总是希望这样做。

  2. 由于我们使用的是标准绑定(而不是SC.Binding.oneWay()),编辑文本字段将自动更新MyApp.myController中对象的someProperty属性,反之亦然:如果您通过其他方式更新值,文本字段也应该自动更新。

  3. 这不应该用于大列表,因为使用视图布局的childViews方法可能会很慢。如果需要性能,应该将exampleView更改为覆盖render()方法的视图,手动呈现文本输入并设置适当的更改事件和绑定。

  4. 最后,我记不清文本字段的valueBinding的正确语法是parentView.content.someProperty还是.parentView.content.someProperty(注意开头的句点)。如果第一种方法不起作用,请尝试添加.,看看它是否起作用。

就像Topher一样,我假设您使用的是SproutCore而不是Ember(以前的SC2)。

如果你需要将任意子视图添加到视图的任意位置,你需要view.appendChild。在按钮的操作中,你可以这样做:

this.get('parentView').appendChild(SC.View.create({ ... }))

如果你走这条路,你必须自己为新视图设计布局。如果你不需要精确控制布局,那么就使用Topher的解决方案——ListView为你完成布局。

最新更新