动态创建input type ='text'框,然后将每个值添加到Backbone.js数组中

时间:2013-04-19 22:03:44

标签: javascript arrays dynamic backbone.js input

我想知道如何基于type ='number'框创建一些文本框...所以只要有人在数字框中加1,另一个文本框字段就会附加到backbone.js查看...然后,当有人在这些文本框中输入值时,将每个值添加到主干模型数组中的某个位置。以下是一些代码:

    <label for='choices'># Choices for Students</label>
    <input type='number' name='choices' step=1 />

    initialize: function(opts) {
    this.model = new QuestionCreateModel({
        mode: null,
        choices: ['A', 'B', 'C'],
        Question: "Question goes here",
        MaxChoices: 0,
        MinChoices: 0,
        WordLimit: 0,
        CharLimit: 0,
    }),

你可以看到,我想取输入type ='number',然后加载文本框,这样我就可以为Backbone模型中的choices数组赋值。

感谢您的帮助!

-Stu

1 个答案:

答案 0 :(得分:0)

我认为你的代码不足。

首先,您需要一个集合和一个模型。

然后创建视图,该视图侦听添加,删除,更改或重置集合的事件。如果您这样做,您的视图将处理这些事件并呈现您应该呈现的任何内容。

myView = Backbone.View.extend({
   initialize : function() {
       this.collection = this.options.collection || new myCollection();
       this.collection.on("add remove reset change", this.render, this)
   },
   events : {
       "change [type='number']" : "numberChanged"
   },
   numberChanged : function(ev) {
       var $el = $(ev.target || ev.srcElement);
       var model = $el.data("model");
       model.set("selectedChoice", $el.val());
   },
   render : function() {
       this.$el.empty();
       this.collection.each(function(model) {
           $("<yourinput>").data("model", model)
               .appendTo(this.$el);
       }, this);
   }
});

现在您的模型和集合

var myModel = Backbone.Model.extend({
   initialize : function() {
      this.on("change:selectedChoice", this.onChoiceChanged, this);
   },
   onChoiceChanged : function(model,value) {
      // from here you know, that a value was selected, you now
      // can say the collection, it should create a new model
      if (this.collection) this.collection.push();
      // this will trigger a "add" event and your "view" will react and rerender.
   }
});

var myCollection = Backbone.Collection.extend({
   model : myModel
});