在骨干中的视图之间传递值

时间:2016-04-12 05:30:42

标签: javascript backbone.js backbone-views backbone-events backbone-collections

我有2个视图,需要在它们之间传递值。

var appModel1 = Backbone.Model.extend({
        url: '/',
        defaults: {
            name: 'Default name'
        },
        validate: function(attr){

        }
    });

    var appCollection1 = Backbone.Collection.extend({
        model: appModel1
    });

    var collection1 = new appCollection1();

    var model1 = new appModel1();
    model1.bind('change', function(){
        model1.save();
    });


    var appView1 = Backbone.View.extend({
        model: model1,
        _modelDataBind: undefined,
        el:'#container1',
        initialize: function(){
            this._modelDataBind = new Backbone.ModelBinder();
            this.render();
        },
        render: function(){
            var template = _.template($('#app1').html());
            this.$el.html(template);
            var bindings = {
                    name: '#txtName'
            };
            var changeTrigger = {
                    'changeTriggers': {
                        '': 'keyup',
                        '#txtName': 'keyup'
                    }
            };
            this._modelDataBind.bind(this.model, this.$el, bindings, changeTrigger);
        },
        'events': {
            'click #btnSubmit': 'addRecord'
        },
        addRecord: function(){
            collection1.push(model1);
            var item = '<li>Name: ' +  model1.get('name') + '</li>';
            var app2 = new appView2({collection: collection1});
            $('#txtName').val('').focus();
        }
    });
    var view1 = new appView1({});


    var appView2 = Backbone.View.extend({
        el: '#container2',
        initialize: function(){
            this.render();
        },
        render: function(){
            var template = _.template($('#app2').html());
            this.$el.html(template);
            this.collection.each(function(model){
                var item = '<li>Name: ' + model.get('name') + '</li>';
                $('#infoList').append(item);
            });
        }
    });
    var view2 = new appView2({});

截至目前,我只能使用集合和id变量传递值。

它们是保留变量吗?

我可以使用任何其他变量传递数据吗?

var app2 = new appView2({nameObj: nameObj});

这失败了。

1 个答案:

答案 0 :(得分:2)

根据文档,Backbone视图仅对选项对象的model, collection, el, id, className, tagName, attributes and events属性起作用。

但是,您可以传递所需的任何其他数据,整个options对象将作为initialize回调的第一个参数。

例如:

var AppView = Backbone.View.extend({
  el: '#container2',
  initialize: function(options){
   // access your data here
    this.valuableInformation = options.valuableInformation;
    if(!options.doNotRender)
      this.render();
  },
  render: function(){
  }
});

new AppView({
  valuableInformation:"it's nothing",
  doNotRender: true
});