在按钮单击事件上绑定dxSelectBox

时间:2014-12-22 11:24:29

标签: javascript jquery mvvm devexpress devextreme

我正在使用DevExtreme MVVM架构,根据我的场景,当按钮点击事件时我需要绑定dxSelectBox(组合框)。

HTML CODE:

<div data-bind="dxButton:{onClick:display,text:'Click Me'}"></div>

<div data-bind="dxSelectBox:{dataSource: themes, displayExpr: 'name' }"></div>

JS CODE:

var themesArray = [
        { themeId: 1, name: "Android (Dunkel)" },
        { themeId: 2, name: "Desktop" },
        { themeId: 3, name: "iOS" },
        { themeId: 4, name: "Windows 8" },
        { themeId: 5, name: "Windows Phone 8" },
        { themeId: 6, name: "Tizen" }
];

var themes = new DevExpress.data.DataSource(themesArray);

var viewModel = {
    themes: '',
    display: function () {
        console.log(themesArray);
        themes: themesArray
    }
};
return viewModel;

提示:dxSelectBox具有空值... 我是这个环境的新手,我不知道我错在哪里..

1 个答案:

答案 0 :(得分:0)

我担心你忘了设置'value'选项,例如:

data-bind="dxSelectBox: { dataSource: [ { val: true, text: 'Yes' }, { val: false, text: 'No' }], valueExpr: 'val', displayExpr: 'text', value: visible }"

根据您的具体情况:

var viewModel = {
themes: [ ...array of themes... ],
selectedThemeId: 1,
display: function () {
    console.log(themesArray);
    themes: themesArray
}
};

data-bind="dxSelectBox: { dataSource: themes, valueExpr: 'themeId', displayExpr: 'name', value: selectedThemeId }"

我厌倦了以下代码:

 var themesArray = [
        { themeId: 1, name: "Android (Dunkel)" },
        { themeId: 2, name: "Desktop" },
        { themeId: 3, name: "iOS" },
        { themeId: 4, name: "Windows 8" },
        { themeId: 5, name: "Windows Phone 8" },
        { themeId: 6, name: "Tizen" }
   ];

  var modifiedthemesArray = [
      { themeId: 1, name: "a (Dunkel)" },
      { themeId: 2, name: "b" },
      { themeId: 3, name: "c" },
      { themeId: 4, name: "Windows 8" },
      { themeId: 5, name: "Windows Phone 8" },
      { themeId: 6, name: "Tizen" }
  ];

  var themes = new DevExpress.data.DataSource(themesArray);

  var viewModel = {
    themes: themesArray,
    selectedThemeId: 1,
    display: function (e) {
        console.log(e);
        themes: modifiedthemesArray
    }
 };
  return viewModel;

您可以使用observableArray更改收藏对象。我厌倦了以下代码,它对我有用:

 var themesArray = [
    { themeId: 1, name: "Android (Dunkel)" },
    { themeId: 2, name: "Desktop" },
    { themeId: 3, name: "iOS" },
    { themeId: 4, name: "Windows 8" },
    { themeId: 5, name: "Windows Phone 8" },
    { themeId: 6, name: "Tizen" }
    ];

    var viewModel = {
        themes: ko.observableArray(),
        display: function() {
            console.log(themesArray);
            viewModel.themes(themesArray);
        }
    };

    return viewModel;