【发布时间】:2016-06-23 20:13:29
【问题描述】:
我们一直在使用Chosen 库和RequireJs 和KnockOut。一切正常,直到我们从RequireJS 切换到commonjs,现在使用webpack 进行捆绑。问题是当我们更改 chosen 下拉列表中的值时,knockout observable 没有更新。
这是使用 RequireJs 工作的 javascript 代码。
define(['knockout', 'text!./employee-setup.html', 'utils', 'panel-section', 'toastr', 'jquery', 'knockout-postbox', 'knockout-projections', 'chosen', 'jsteps'], function (ko, template, utils, PanelSection, toastr, $, _, _, _, jsteps) {
function EmployeeSetup(params) {
var self = this;
this.agentTypes = ko.observableArray();
this.agentType = ko.observable();
this.loadAgentTypes = function () {
$.ajax({
url: '/Employee/GetAgentTypes',
method: 'POST',
dataType: 'json',
success: function (result) {
if (utils.handleAjaxResult(result) && result.Data) {
self.agentTypes([]);
var agentType = [{ ID: "", Name: "" }];
$.each(result.Data, function (i, item) {
agentType.push({ID: item.ID, Name: item.Name});
});
self.agentTypes(agentType);
$('#agentType').chosen({ allow_single_deselect: true, width: '310px' });
$('#agentType').trigger("chosen:updated");
} else {
}
},
error: function () {
toastr.error('Could not load agent types');
}
});
};
self.loadAgentTypes();
};
return { template: template, viewModel: EmployeeSetup };
});
该组件的 html:
<div class="input-container" data-bind="">
<select data-bind="value: agentType, options: agentTypes, optionsText: 'Name'" data-placeholder="Select Agent Type..." id="agentType" class="chosen-select sp-uin-dropdown" tabindex="2"> </select>
</div>
这是使用commonjs的代码
var ko = require('knockout'),
utils = require('utils'),
PanelSection = require('panel-section'),
toastr = require('toastr'),
$ = require('jquery');
require('knockout-postbox');
function ViewModel(params) {
var self = this;
this.agentTypes = ko.observableArray();
this.agentType = ko.observable();
this.loadAgentTypes = function () {
$.ajax({
url: '/Employee/GetAgentTypes',
method: 'POST',
dataType: 'json',
success: function (result) {
if (utils.handleAjaxResult(result) && result.Data) {
self.agentTypes([]);
var agentType = [{ ID: "", Name: "" }];
$.each(result.Data, function (i, item) {
agentType.push({ID: item.ID, Name: item.Name});
});
self.agentTypes(agentType);
$('#agentType').chosen({ allow_single_deselect: true, width: '310px' });
$('#agentType').trigger("chosen:updated");
} else {
}
},
error: function () {
toastr.error('Could not load agent types');
}
});
};
self.loadAgentTypes();
}
module.exports = { viewModel: ViewModel, template: require('./template.html') };
它使用与上面相同的html 文件。
在webpack.config.js 中,我们定义了jquery 和chosen 的路径。
它会正确加载chosen dropdown。但是,当我 subscribe 观察到时,它不会在下拉列表更改时更新值。我只在初始加载时从控制台看到过一次值。
self.agentType.subscribe(function (value) {
console.log('value', value);
}, this)
这里很少有帖子建议使用bindingHandlers。我在我的应用程序中尝试了来自JSFiddle 的工作代码,但我只从初始加载中获取值。
关于如何解决此问题或导致此问题的任何建议?
【问题讨论】:
标签: knockout.js webpack jquery-chosen commonjs