如何使用backbone.js创建单独的模型,视图和控制器

时间:2012-05-09 04:50:46

标签: javascript backbone.js

  • 我再次编辑我的代码,我收到以下2个错误:

1)未定义Complex_collection

  model: Complex_model

2)未定义Complex_model

 model: Complex_model

我正在使用骨干js以下是我的代码,我使用backbone.js完成此操作,但我的代码没有运行我想要使用骨干js的单独模型,视图和控制器

//模型

(function(){ var Complex_model = Backbone.Model.extend({        
    sync:function() {},
    validate:function() {},
    url:function() {},          
    defaults :{
        name : null
    }    
});})(this);

//视图

(function(){

FriendView = Backbone.View.extend({
    events :{
        'click #add-input' : 'add'
    },
    initialize: function(){
        this.collection = new Complex_collection(); // This is collection
        _.bindAll(this, 'render');
    },      
    add : function() {
        alert("hello");
        var friend_name = $('#input').val();
        this.collection.add({ name : friend_name });
    },
    render : function(){
        $("#friends-list").append("<li>"+ model.get("name")+"</li>");
    },      
});

var view = new FriendView(); })(this);

//收集

(function(){    

    var Complex_collection = Backbone.Collection.extend({

    model: Complex_model

});})(this);

谢谢

1 个答案:

答案 0 :(得分:0)

你不应该在初始化代码中创建同一个对象的新实例,你的代码应该是这样的:

(function(){ 
    this.complex_model = Backbone.Model.extend({        
        sync:function() {},
        validate:function() {},
        url:function() {},      
    });
})(this);

// View

(function(){
    var vw = view = function(){};
    FriendView = Backbone.View.extend({
        events :{
            'click #add-input' : 'add'
        },
        initialize: function(){
            this.friendslist = new FriendList(); // This is your collection right?
            _.bindAll(this, 'render');
        },      
        add : function() {
            var friend_name = $('#input').val();
            this.friendslist.add({ name : friend_name });
        },
        render : function(){
            $("#friends-list").append("<li>"+ model.get("name")+"</li>");
        },      
    });
})(this);

// Collection
(function(){    this.complex_collection = Backbone.Collection.extend({
    model : complex_model
});})(this);

// Your main app
var view = new FriendView();