在按钮单击事件上绑定 dx选择框

Bind dxSelectBox on button click event

本文关键字:dx 选择 绑定 按钮 单击 事件      更新时间:2023-09-26

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

网页代码:

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

JS代码:

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 具有空值...我是这个环境的新手,我不知道我在哪里做错了。

怕你忘了设置"值"选项,例如:

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;