【问题标题】:dynamically create input type='text' boxes then add values from each into Backbone.js array动态创建输入 type='text' 框,然后将每个框的值添加到 Backbone.js 数组中
【发布时间】:2013-04-19 22:03:43
【问题描述】:

我想知道如何基于 type='number' 框创建多个文本框...所以一旦有人将 1 添加到数字框,另一个文本框字段将附加到主干.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 模型中的选择数组。

感谢您的帮助!

-斯图

【问题讨论】:

    标签: javascript arrays dynamic backbone.js input


    【解决方案1】:

    我觉得你的代码不够用。

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

    然后你创建你的视图,它监听集合的添加、删除、更改或重置事件。如果你这样做,你的视图将处理这些事件并呈现你说它应该呈现的任何东西。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多