繁体   English   中英

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

[英]dynamically create input type='text' boxes then add values from each into Backbone.js array

我想知道如何根据type ='number'框创建多个文本框...因此,只要有人将1添加到数字框中,另一个文本框字段就会附加到ribs.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数组分配值。

谢谢您的帮助!

-斯图

我认为您的代码不足。

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

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

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
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM