Lightning Message Channel的使用方法(未完成)
2023年08月23日
文章浏览:258
前言,关于Lightning Message Channel


大家可能会经常听到Pub/Sub通信模式。

在Salesforce上面,如果我们要用到Pub/Sub通信模式,那么最简单的就是使用Lightning Message Channel。

要用Lightning Message Channel之前,我们需要做一些准备工作,去定义messageChannels的内容,然后部署到Salesforce环境上面。


定义messageChannels.xml文件


如果我们要传递recordId和recordData,那么我们就需要定义如下的XML文件


<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <fieldName>recordId</fieldName>
    </lightningMessageFields>
    <lightningMessageFields>
        <fieldName>recordData</fieldName>
    </lightningMessageFields>
    <masterLabel>Sample Message Channel</masterLabel>
</LightningMessageChannel>


publisherComponent.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <lightning:button label="Send Payload" onclick="{! c.handleClick }"/>
    <lightning:messageChannel type="SampleMessageChannel__c"
            aura:id="sampleMessageChannel"/>
</aura:component>
publisherComponentController.js
// publisherController.js
({
    handleClick: function(cmp, event, helper) {
        var payload = {
            recordId: "some string",
            recordData: {
    value: "some value"
}
        };

        cmp.find("sampleMessageChannel").publish(payload);
    }
})






subscriberComponent.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	  <aura:attribute name="recordValue" type="String"/>
    <lightning:formattedText value="{!v.recordValue}" />
    <lightning:messageChannel type="SampleMessageChannel__c"
            onMessage="{!c.handleChanged}" scope="APPLICATION"/>
</aura:component>
subscriberComponentController.js
// subscriberController.js
({
    handleChanged: function(cmp, message, helper) {
        // Read the message argument to get the values in the message payload
    if (message != null && message.getParam("recordData") != null) {
        cmp.set("v.recordValue", message.getParam("recordData").value);
    }
    }
})


??

关注 收藏