首页 > 代码库 > backbone.js

backbone.js

<!DOCTYPE html>
<html>
<head>
    <title>backbone</title>
    <script src="http://www.mamicode.com/js/jquery-3.1.1.js"></script>
    <script src="http://www.mamicode.com/js/underscore-1.8.3.js"></script>
    <script src="http://www.mamicode.com/js/backbone-1.3.3.js"></script>
    <script>
   $(function(){
    //model
    Person = Backbone.Model.extend({
        //默认属性
        defaults: {
            name: ‘Fetus‘,
            age: 0,
            children: []
        },
        // 如果从validate中返回字符串了, Backbone就会抛个实例异常
        validate: function(attrs){
            if( attrs.age < 0 && attrs.name != "Dr Manhatten" ){
                return "你的存在是个错误"+attrs.name;
            }
        },
        initialize: function(){       
            alert("A brand new day!");
        }
    });
    
    var person = new Person();
    //alert("欢迎来到这个报错的世界");
    person.on("invalid", function(model, error){
        // 收到个错误,记录,警告,然后忘记它。╮(‵▽′)╭
        alert( error );
    });
    
    // 会触发error,输出警告
    person.set({ name: "pattern1", age: -1 ,children: [‘Ryan‘]});
    person.set({ name: "pattern5", age: -1 ,children: [‘Ryan‘]},{validate:true});
    person.set({ name: "pattern6", age: -1 ,children: [‘Ryan‘]});
    person.save({ name: "pattern2", age: -1 ,children: [‘Ryan‘]});     
    delete person;
    var person = new Person();
    person.on("invalid", function(model, error){
        // 收到个错误,记录,警告,然后忘记它。╮(‵▽′)╭
        alert( error );
    });
    person.set({ name: "pattern3", age: -1 ,children: [‘Ryan‘]});
    var a=person.isValid();
    if (!a) {
        alert("pattern4" + person.validationError);
    }
   })
    </script>
</head>
<body>
    <button id="check">新手报到</button>
    <ul id="world-list">
    </ul>
    
</body>
</html>

 

backbone.js