uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

backbonejs #6

Open uniquejava opened 8 years ago

uniquejava commented 8 years ago

模板代码:

Model

var Human = Backbone.Model.extend({
  defaults: {
    name: 'Fetus',
    age: 0,
    child: ''
  },
  initialize: function(){
    alert("Welcome to this world");
  },
  adopt: function( newChildsName ){
    this.set({ child: newChildsName });
  }
});

var human = new Human({ name: "Thomas", age: 67, child: 'Ryan'});
human.adopt('John Resig');
var child = human.get("child"); // 'John Resig'

View

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
  var SearchView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    render: function(){
      // Compile the template using underscore
      var template = _.template( $("#search_template").html(), {} );
      // Load the compiled HTML into the Backbone "el"
      this.$el.html( template );
      return this;
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });
</script>

Collection


var Song = Backbone.Model.extend({
  defaults: {
    name: "Not specified",
    artist: "Not specified"
  },
      initialize: function(){
          console.log("Music is the answer");
      }
  });

  var Album = Backbone.Collection.extend({
  model: Song
});

var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });

var myAlbum = new Album([ song1, song2, song3]);
console.log( myAlbum.models ); // [song1, song2, song3]

Router

var AppRouter = Backbone.Router.extend({
    routes: {
        "*actions": "defaultRoute"
        // matches http://example.com/#anything-here
    }
});
// Initiate the router
var app_router = new AppRouter;

app_router.on('route:defaultRoute', function(actions) {
    alert(actions);
});

// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start();

History

Sync

可以在Model或Collection中覆盖sync方法如下:

I typically need to override backbone's sync method when I need to only sync certain attributes. A typical implementation looks like this:

sync: function (method, model, options) {
  options.data = _.pick(this.attributes, 'foo', 'bar', 'baz');
  return Backbone.sync.call(this, method, model, options);
}

这里有lcoalStorage是如何重写Sync方法的: http://backbonejs.org/docs/backbone.localStorage.html

uniquejava commented 8 years ago

Lessons learned

  1. 不要给view指定el: '#content', 每个view应该有各自的div, 这是因为在changeView的时候会调用view.remove()会将当前的#content给干掉,导致接下来的view无法显示到页面上
uniquejava commented 8 years ago

Router

如何以编程的方式添加新的route http://stackoverflow.com/questions/9595182/programmatically-adding-routes-to-backbone-router

var AppRouter = Backbone.Router.extend({
    routes: {
        "": 'showDashboard',
       '/test/me': function(){},
        "*actions": "defaultRoute"
    },
    defaultRoute: function(actions){},
    testMeAgain: function(){}
});
// Initiate the router
var app_router = new AppRouter;

app_router.on('route:defaultRoute', function(actions) {
    alert(actions);
});

// 以下这句没起作用, 原因是通过route方法添加的route会放到routes的最后,
// 也就是放在了*actions的最后,所以没起作用,
// 解决办法是把*actions从routes中移除, 然后以编程的方式放在下面这句的后面。
app_router.route('/test/me/again', 'testMeAgain');

// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start();

如果console.log(app_router)会发现并没有这个对象中并没有全部的routes,这是因为route方法将新的route放到了Backbone.history里边。见这里

route: function(route, name, callback) {
  // ...
  Backbone.history.route(route, _.bind(function(fragment) {
    //...
  }, this));
  return this;
},
uniquejava commented 8 years ago

继承测试

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
    <script type="text/javascript" src="bower_components/underscore/underscore-min.js"></script>
    <script type="text/javascript" src="bower_components/backbone/backbone.js"></script>
</head>
<body>
<div id="content">

</div>

<script type="text/javascript">
    var ListView = Backbone.View.extend({
        el: '#content',

        number: 5,

        initialize: function () {
            this.render();
        },

        render: function(){
            this.$el.html(this.getNumber());
        },

        getNumber: function(){
            return this.number;
        }

    });

    var CustomListView = ListView.extend({
        number: 6
    });

    var view = new CustomListView();

</script>

</body>
</html>