Django+Tastypie作后端,RequireJS+Backbone作前端的TodoMVC

一、配置好环境

接着前一篇的例子,顺带测试一下已下载下来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提供了!

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。