所以我测试了一下,发现当我以这种方式设置代码时,订阅函数永远不会被调用:
requirejs.config({
"baseUrl": "/Scripts/app/item/",
"paths": {
"jquery": "//code.jquery.com/jquery-2.0.3.min",
"toastr": "/Scripts/lib/toastr",
"moment": "/Scripts/lib/moment",
"fu": "/Scripts/lib/jquery.fineuploader-3.8.0",
"ko": "//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min",
"knockout.validation": "/Scripts/lib/knockout.validation",
"mapping": "/Scripts/lib/knockout.mapping-latest.debug",
"timeentry": "/Scripts/lib/jquery.timeentry.min",
"model.obj": "../models/model.obj",
"timecollection.kobindings":"/Scripts/lib/koBindings/timecollection.kobindings"
},
shim: {
"knockout.validation": ["ko"],
"mapping": ["ko"]
}
});
require(["ko"], function (ko) {
//manually set the global ko property
window.ko = ko;
//then bring in knockout validation
require(["knockout.validation"], function () {
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error'
});
require(["main.index"], function (bs) {
bs.run();
});
});
});
define(['jquery',
'ko',
'mapping',
'indexViewModel',
'model.obj'],
function ($, ko, mapping, indexViewModel, obj) {
var
run = function () {
var vm = new indexViewModel();
var array = [];
$.getJSON("/api/GetData/", function (data) {
mapping.fromJS(val.ObjCollection, {
create: function (options) {
return new Obj(options.data);
}
}, vm.ObjCollection);
}).done(function(){
ko.applyBindings(vm, document.getElementById('#view'));
});
};
return {
run: run
};
});
define('model.obj', ['ko', 'moment'], function (ko, moment) {
var Obj= function (data) {
var self = this;
self.Id = data.Id;
self.Property = ko.observable(data.Property);
self.Property .subscribe(function () {
console.log('in here');
}, self);
};
return Obj;
});
如果我删除此代码:
require(["ko"], function (ko) {
//manually set the global ko property
window.ko = ko;
//then bring in knockout validation
require(["knockout.validation"], function () {
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error'
});
require(["main.index"], function (bs) {
bs.run();
});
});
});
然后就这样离开:
require(["main.index"], function (bs) {
bs.run();
});
订阅功能会显示console.log,但是使用代码,订阅永远不会被调用。
答案 0 :(得分:1)
您的代码中存在语法错误:
function ($, ko, mapping, indexViewModel, obj) {
var
run = function () {
var vm = new indexViewModel();
var array = [];
$.getJSON("/api/GetData/", function (data) {
mapping.fromJS(val.ObjCollection, {
create: function (options) {
return new Obj(options.data);
}
}, vm.ObjCollection);
注意到你'返回新的Obj'(带资本),但是模块作为'obj'注入函数(没有资本)。这可以解释为什么你永远不会到达那里(虽然它没有解释为什么淘汰验证与它有任何关系)。
如果这对您没有帮助,请在代码的各个部分放置一些断点,然后单步执行。查看问题出现的位置。整个部分永远不会被触发,还是仅仅是未触发的订阅?为什么你期望订阅回调首先触发?您首先设置值,然后订阅,但如果您再也不更新该值,则回调永远不会触发。