Mixpanel 2.2 within an AMD structured web-app - e.g. require.js

后端 未结 4 633
[愿得一人]
[愿得一人] 2021-02-06 09:55

I\'m attempting to make use of Mixpanel event tracking in a single page site based on Backbone.js and require.js.

Looking at the snippet that Mixpanel provide for cut-an

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 10:15

    There are two funny things that makes this an odd problem to solve:

    1. The mixpanel lib requires you to have window.mixpanel defined before you load it.
    2. The mixpanel lib re-defines window.mixpanel as a part of its init process.

    Out of the box, the mixpanel snippet doesn't support get_distinct_id (and any call that is, by definition, synchronous) until the lib is loaded but does stub out other methods (such as track) BEFORE loading the mixpanel lib for the sake of queueing. Therefore we have two options:

    Option 1. Drop async support and wait until the lib is loaded - Gist

    This method works by creating a pre-init module to setup the window.mixpanel deps needed by the mixpanel lib and then specifying that as a dependency to the lib itself. Then requiring "mixpanel" will block until the lib is fully loaded.

    
        
            Mixpanel AMD Example - Sync
            
            
        
        
            
        
    
    

    Option 2. Provide a "loaded" callback to update the module's properties. - Gist

    If you REALLY want async support, you'll need to update your stub's methods once the mixpanel lib is loaded. I don't recommend this because (among other reasons) it results in window.mixpanel !== mixpanel after the copy. This also means you must protect against race conditions on synchronous calls like get_distinct_id(). If the lib hasn't loaded yet, it'll be undefined. NOTE: I recommend that if you must have async support, you should just call through window.mixpanel instead of all of this craziness.

    
        
            Mixpanel AMD Example - Async
            
            
        
        
            
        
    
    

提交回复
热议问题