knockout.js Magento从一个mixin访问jsLayout配置数据

vddsk6oq  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(171)

我想扩展一个knockout组件的功能。我已经将配置添加到所讨论的xml文件中:

  1. <arguments>
  2. <argument name="jsLayout" xsi:type="array">
  3. <item name="components" xsi:type="array">
  4. ...
  5. <item name="example">
  6. ... other properties of the component
  7. <item name="config" xsi:type="array">
  8. <item name="SomeConfigVariable" xsi:type="string">true</item>
  9. </item>
  10. </item>
  11. ...
  12. </item>
  13. </argument>
  14. </arguments>

我已经使用我的模块requirejs-config.js包含了mixin,我可以看到它在我的浏览器中遇到了一个断点。

  1. var config = {
  2. config: {
  3. mixins: {
  4. "Magento_MODULE/js/view/example": {
  5. "VENDOR_MODULE/js/view/example-mixin": true,
  6. }
  7. },
  8. },
  9. };

然而,我似乎找不到必要的代码来获取我的配置数据,我已经尝试了这个:

  1. define(["ko"], function (ko) {
  2. var mixin = {
  3. imports: {
  4. someConfigVariable: "${ $.SomeConfigVariable }", // Doesn't seem to do anything
  5. },
  6. initialize: function () {
  7. this.someConfigVariable = false; // Default value
  8. this._super();
  9. return this;
  10. },
  11. };
  12. return function (target, config) { // config is undefined
  13. return target.extend(mixin);
  14. };
  15. });

我错过了什么?

jljoyd4f

jljoyd4f1#

mixin代码并不是绝对必要的。将其设置为默认值,如下所示:

  1. define(["ko"], function (ko) {
  2. var mixin = {
  3. defaults: {
  4. someConfigVariable: false,
  5. },
  6. initialize: function () {
  7. this._super();
  8. return this;
  9. },
  10. };
  11. return function (target) {
  12. return target.extend(mixin);
  13. };
  14. });

以及更新布局XML以如下所示:

  1. <arguments>
  2. <argument name="jsLayout" xsi:type="array">
  3. <item name="components" xsi:type="array">
  4. ...
  5. <item name="example">
  6. ... other properties of the component
  7. <item name="config" xsi:type="array">
  8. <item name="SomeConfigVariable" xsi:type="boolean">true</item> <!-- Note the xsi:type as boolean -->
  9. </item>
  10. </item>
  11. ...
  12. </item>
  13. </argument>
  14. </arguments>

在运行组件时得到我想要的结果。Magento在点击initConfig方法之前对config元素做了一些魔法。

展开查看全部

相关问题