MVC简述

创建模型

let M = Backbone.Model.extend({})

var Man = Backbone.Model.extend({
    initialize: function(){
        alert('Hey, you create me!');
        //初始化时绑定监听, change事件会先于validate发生
        this.bind("change:name",function(){
            var name = this.get("name");
            alert("你改变了name属性为:" + name);
        });
        this.bind("invalid",function(model,error){
            alert(error);
        });
    },
    defaults: {
        name:'张三',
        age: '38'
    },
    validate:function(attributes){
        if(attributes.name == '') {
            return "name不能为空!";
        }
    },
    aboutMe: function(){
        return '我叫' + this.get('name') + ',今年' + this.get('age') + '岁';
    }
});
var man = new Man;
// 这种方式添加错误处理也行
// man.on('invalid', function(model, error){
//         alert(error);
// });

//默认set时不进行验证
man.set({name:''});
//手动触发验证, set时会触发
//man.set({name:''}, {'validate':true});

创建集合

  let Book = Backbone.Model.extend({
    defaults: {
      title: 'default'
    },
    initialize: function() {
      alert('123')
    }
  })

  let BookShelf = Backbone.Collection.extend({
    model: Book
  })

  let book1 = new Book({title: 'book1'})
  let book2 = new Book({title: 'book2'})
  let book3 = new Book({title: 'book3'})

  let bookShelf = new BookShelf;

  bookShelf.add(book1)
  bookShelf.add(book2)
  bookShelf.add(book3)
  bookShelf.remove(book3)

  console.log('bookShelf', bookShelf)

创建视图

Backbone的View是用来显示你的model中的数据到页面的,同时它也可用来监听DOM上的事件然后做出响应
let V = Backbone.View.extend({})

var SearchView = Backbone.View.extend({
  initialize: function(){
  },
  render: function(context) {
      //使用underscore这个库,来编译模板
      var template = _.template($("#search_template").html());
      //加载模板到对应的el属性中
      $(this.el).html(template(context));
  },
  events: {
    // 绑定方法
    'click input[type=button]' : 'doSearch'
  },
  doSearch: function(event){
      alert("search for " + $("#search_input").val());
  }
});
var searchView = new SearchView({el: $("#search_container")});

//这个reander的方法可以放到view的构造函数中
//这样初始化时就会自动渲染
searchView.render({search_label: "搜索渲染"});

常用方法

  1. Model/Collcetion/View - initialize: 初始化
  2. View - listenTo: 监听对象
  3. Model - this.bind("change:name",function(){})

常用配置

  1. View - events: 绑定事件

你可能感兴趣的:(MVC简述)