標籤:
一、配置好環境
接著前一篇的例子,順帶測試一下已下載下來example裡面的backbone_require的例子
注意:直接本地用backbone.localStorage外掛程式運行TodoMVC會報錯,因為RequireJS工作時,載入js檔案及template檔案是非同步載入,這就好比ajax非同步請求需要涉及到跨域的問題,檔案必須要在同一下域下才能被非同步載入。
因此,直接把所有檔案放到上篇檔案的static(E:\project\tastypie\mysite\blog\static)目錄下,把django啟動一下就可以了,用backbone.localStorage本地運行,在瀏覽器輸入http://localhost:8000/static/index.html 此時應該可以正常運行TodoMVC了
二、把backbone.localStorage切換到本地串連tastypie的api介面的url
1)改backbone的model檔案與collection檔案
E:\project\tastypie\mysite\blog\static\todos\js\models\todo.js 添加urlRoot為tastypie的api介面
app.Todo = Backbone.Model.extend({。。。 urlRoot: ‘/api/v1/todo/‘,。。。 });
改E:\project\tastypie\mysite\blog\static\todos\js\collections\todos.js
/*global define */define([ ‘underscore‘, ‘backbone‘, //‘backboneLocalstorage‘, //1,這個模組不需要用到,注釋掉 ‘models/todo‘], function (_, Backbone,Todo) {//1,跟據RequireJS規範這裡把store刪掉 ‘use strict‘; var TodosCollection = Backbone.Collection.extend({ // Reference to this collection‘s model. model: Todo, // Save all of the todo items under the `"todos"` namespace. //localStorage: new Store(‘todos-backbone‘), //2,這裡也不需要用到 url: ‘/api/v1/todo/‘, //3,配置api介面,跟上篇一樣 parse: function (response) {//4,取到objects真正資料,把meta資料過濾掉 return response.objects; }, // Filter down the list of all todo items that are finished. completed: function () { return this.where({completed: true}); }, // Filter down the list to only todo items that are still not finished. remaining: function () { return this.where({completed: false}); }, // We keep the Todos in sequential order, despite being saved by unordered // GUID in the database. This generates the next order number for new items. nextOrder: function () { return this.length ? this.last().get(‘id‘) + 1 : 1;//5,把order改為id,因為我們資料庫裡面是自動產生了遞增的id預設是0,1,2... }, // Todos are sorted by their original insertion order. comparator: ‘order‘ //無影響切換過來後沒用到 }); return new TodosCollection();});
2)最後E:\project\tastypie\mysite\blog\static\js\views\app.js 把appview檔案中的order改為id
// Generate the attributes for a new Todo item. newAttributes: function () { return { title: this.$input.val().trim(), id: Todos.nextOrder(), completed: false }; },
搞定,可以測試一下!http://localhost:8000/static/index.html 此時應該可以正常運行TodoMVC了,資料是由sqlLite提供了!
Django+Tastypie作後端,RequireJS+Backbone作前端的TodoMVC