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提供了!

 

转载于:https://www.cnblogs.com/fastmover/p/4280605.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值