Я пытаюсь написать простое приложение с использованием backbone.js, которое в конце должно сохранять модели в indexedDB и отображать их. Я свободно основал его на приложении todo в примерах основы. Он отлично работает, когда я не использую require.js.require.js и backbone.js получение Uncaught TypeError
Когда я пытаюсь использовать require, хотя я получаю Uncaught TypeError: Object # не имеет ошибки метода 'on', которая, кажется, указывает на точку, где я добавляю некоторые eventlisteners в одном из моих представлений.
Мои файлы упорядочены следующим образом: в папке «js» находятся папки «app», «lib» и «tpl» и main.js. В приложении есть папка «controller» с taskItemView и taskListView и папка «model» с моей taskModel.js и database.js. В папке «lib» находятся мои внешние библиотеки, backbone, underscore, jquery, json2, require, text, адаптер для indexedDB backbone-indexeddb.js и прокладка для браузеров, которые поддерживают только websql, IndexedDBShim.js.
Это мой main.js, который я пытаюсь настроить.
require.config({
baseUrl: "js/lib",
paths: {
app: '../app',
tpl: '../tpl'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'underscore': {
exports: '_'
},
'backbone-indexeddb': {
deps:['backbone']
},
'IndexedDBShim': {
deps:['backbone']
}
}
});
require(
['backbone', 'app/router'], function (Backbone, Router) {
var router = new Router();
Backbone.history.start();
}
);
Я получаю сообщение об ошибке 22 строки в моей taskListView, здесь.
define(function (require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
_ = require('underscore'),
//Template = require('text!tpl/taskListView.html'),
taskList = require('app/model/taskModel');
//the collection for our tasks
//var Tasks = new TaskList;
//this will handle all the user inputs and the output for the gui.
return Backbone.View.extend({
el: $("#taskApp"),
//on enter keypress fires createOnEnter
events: {
"keypress #taskInput": "createOnEnter",
},
//initializes the app
initialize: function() {
//listeners
this.listenTo(taskList, 'add', this.addOne); //this is where the error comes from.
this.listenTo(taskList, 'all', this.render);
//get the template
//var template = _.template(Template);
template: _.template($('#taskListView').html()),
//apply template
this.$el.html(template);
//get text input field
this.input = this.$("#taskInput");
this.main = $('#main');
//fetch old entries
taskList.fetch();
},
//renders the main section
render: function() {
this.main.show();
},
//appends an item to the list
addOne: function (taskModel) {
var view = new taskItemView({
model: taskModel
});
this.$("#taskList").append(view.render().el);
},
//creates a new item from the text input field
createOnEnter: function (e) {
//check for valid input (enter)
if (e.keyCode != 13) return;
//check if input is empty
if (!this.input.val()) return;
//get data
var inputData = this.input.val();
//creates and adds new item to collection
taskList.create({
title: inputData
});
//clear input field
this.input.val('');
},
});
});
Просто для завершения, это мой taskItemView:
define(function (require){
"use strict";
var $ = require('lib/jquery'),
_ = require('lib/underscore'),
Backbone = require('lib/backbone');
//Template = require('lib/text!tpl/taskItemTemplate.html');
//manage task items and binding
return Backbone.View.extend({
tagName: "li",
classname: "topcoat-list__item",
//template used for task Items
template: _.template($('#taskItemView').html()),
//template: _.template(Template),
//initialize, create listener for changes in model
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
//use template to display task items
render: function() {
//fetch JSON representation of model
var modelJSONrepresentation = this.model.toJSON();
//inject into template
var templating = this.template(modelJSONrepresentation);
//apply template
this.$el.html(templating);
return this;
}
});
});
Моя модель:
define(function (require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
//taskDatabase = require('app/model/database'),
//manage task items
task = Backbone.Model.extend({
//bind indexedDB
//database: taskDatabase,
//storeName: "tasks",
defaults: function() {
return {
title: "test"
};
}
}),
//manage list of tasks
taskList = Backbone.Collection.extend({
//bind model
model: task,
//bind indexedDB
//database: taskDatabase,
//storeName: "tasks"
});
return {
task: task,
taskList: taskList
};
});
База данных менеджер
define(function (require){
"use strict";
//create indexedDB
var taskDatabase = {
id: "taskDataBase4",
description: "The Database used in the TaskList App",
migrations: [{
version: 1,
migrate: function (transaction, next) {
var store = undefined;
//create store if it doesn't exist already
if (!transaction.db.objectStoreNames.contains("tasks")) {
store = transaction.db.createObjectStore("tasks")
}
store = transaction.objectStore("tasks");
next();
}
}]
}
});
И мой маршрутизатор. Я не использовал его в приложении non-require.js, но я должен использовать его здесь.
define(function (require){
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
TaskListView = require('app/controller/taskListView');
taskListView = new TaskListView();
return Backbone.Router.extend({
routes: {
"": "home"
},
home: function() {
console.log("derp");
taskListView.delegateEvents();
}
});
});
Я нахожусь в недоумении и навсегда благодарен.
Edit: полный стек ошибок:
Uncaught TypeError: Object #<Object> has no method 'on' backbone.js:226
Events.(anonymous function) backbone.js:226
Backbone.View.extend.initialize taskListView.js:22
Backbone.View backbone.js:1002
child backbone.js:1567
(anonymous function) router.js:9
context.execCb require.js:1650
Module.check require.js:866
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
Module.enable require.js:1143
Module.init require.js:774
callGetModule require.js:1170
context.completeLoad require.js:1544
context.onScriptLoad
Этот файл ссылается как «Моя модель» на файл, импортируемый 'taskList = require ('app/model/taskModel');'? – max