Magento 2 – Replace Prototype JS with jQuery

jquerymagento2prototype-jsrequirejs

default.xml

<?xml version="1.0"?>
<page
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Ei_Productpoint::js/productpoint-slider.js"/>
    </head>
    <body/>
</page>

requirejs-config.js

var config = {
    map: {
        '*': {
            MySlider: 'Namespace_Modulename/js/productpoint-slider'
        }
    }
};

productpoint-slider.js (Prototype JS)

 define(['prototype'],function($){
 // where $ == "prototype"
var MySlider = Class.create();
MySlider.$ = {
initialize: function(amountR, trackR, handleR, decrHandleR, incrHandleR, minPointR, maxPointR, stepR, labelAmountR, checkMaxAmountR) {

        this.minPointsCheck = minPointR;
        this.minPoints = 0;
        this.maxPoints = maxPointR;
        this.pointStep = stepR;

        this.mwSlider = new Control.Slider(this.handleR, this.trackR, {
        range: $R(this.minPoints, this.maxPoints),
        values: this.mwAvailableValue(),
        onSlide: this.changeProductPoint.bind(this),  
        onChange: this.changeProductPoint.bind(this)
    });
    },
    mwAvailableValue: function() {
        var values = [];
        for (var i = this.minPoints; i <= this.maxPoints; i += this.pointStep) {
            values.push(i);
        }
        return values;
    }
}

return MySlider;
});

Call to JS function

<script type="text/javascript">

    var productPointVal = '<?php echo $maxPoints; ?>';
    var pointsRedeem = '<?php echo $pointsRedeem; ?>';
    var time = 1000;
    var time_new = 1500;
    var timer;
    var ei_sider = new MySlider(
            'product_point',
            'ei_productpoint_slider_container',
            'ei_slider',
            'ei_productpoint_decr_handle',
            'ei_productpoint_incr_handle',
            0,
            productPointVal,
            1,
            'ei_label_amount'
            );
</script>

Below exception is seen in console.

ReferenceError: MySlider is not defined
var ei_sider = new MySlider(

Followed this link, to use something with similar syntax to the way PrototypeJS handles it, but after including the JS, its not working in Magento 2.0 and throws below exception

TypeError: this.mwSlider is undefined
points = this.mwSlider.getNearestValue(parseInt(points));
  1. How do I convert existing prototype js into jquery so
    that it works in 2.0 ?

    OR

  2. How do I make prototype js work ?

Best Answer

UnderscoreJs library was created when RoR migrate from prototypejs to jquery. You may use it to migrate your scripts. For example Class.create is _.create