logo
down
shadow

Issue attaching javascript events using variation on module pattern


Issue attaching javascript events using variation on module pattern

By : 林佳威
Date : November 22 2020, 02:59 PM
it helps some times I'm trying to attach Javascript events to SVG elements using code that is inside the "module pattern". I'm very new to Javascript, as I'm sure will be evident by the code below. I've attempted to recreate the situation using a much simpler version of the code I am actually using. Ironically, I am actually further away from getting it to work with this example, but my brain hurts from attempting to get it to work and researching elsewhere on this site. So, I am reaching out to all the clever people out there to see if they can help. The problem I am having (when I get it to work!) is that the Javascript events do not appear to be binding to the DOM elements and just firing on page load. When I then fire the event again (by moving the mouse) I get a Javascript error caused by the D3 library: , Problem1: The event gets fired on page load
Reason:
code :
.on("mouseover", mouseOver(target)) //this is wrong the second parameter should have been a function.
.on("mouseover", function(){mouseOver(target)})
tt.control = tt.box.append("rect")
                            .attr({
                                "fill": "none",//this should not be none else mouse over will not work as you expect
                                "width": 50,
                                "height": 50,
                            })
                            .on("mouseover", mouseOver(target))
                            .on("mouseout", mouseOut(target))
for (target in this.targets) {
            tt = this.targets[target]
            tt.control = tt.box.append("rect")
              .attr({
                "fill": "blue",
                "width": 50,
                "height": 50,
                "opacity": 0
              })
  for (target in this.targets) {
    tt = this.targets[target]
    tt.control = tt.box.append("rect")
      .attr({
        "fill": "blue",
        "width": 50,
        "height": 50,
        "opacity": 0
      })

      .on("mouseover", function() {
        mouseOver(tt)
      })
      .on("mouseout", function() {
        mouseOut(tt)
      });
      tt.control.node().dataset = tt;//binding the data to the dom
  };
function mouseOver(target) {
      //gettting the data from the dom
      event.target.dataset.circle.attr("fill", "blue");
    }

    function mouseOut(target) {
      event.target.dataset.circle.attr("fill", "green");
    }


Share : facebook icon twitter icon
Javascript Module Pattern Events and Listeners

Javascript Module Pattern Events and Listeners


By : user3757528
Date : March 29 2020, 07:55 AM
like below fixes the issue Normally, I wouldn't respond to an architectural question with a specific implementation (especially one dependent on a 3rd-party library like jQuery), but since my implementation promotes reusability — and we are talking patterns here — I will present a small jQuery plugin, $.eventable, which augments JavaScript objects with jQuery's event methods.
This plugin will allow you to implement event handling capability on any object (or class instance) with one simple call.
code :
jQuery.eventable = function (obj) {
  // Allow use of Function.prototype for shorthanding the augmentation of classes
  obj = jQuery.isFunction(obj) ? obj.prototype : obj;
  // Augment the object (or prototype) with eventable methods
  return $.extend(obj, jQuery.eventable.prototype);
};

jQuery.eventable.prototype = {

  // The trigger event must be augmented separately because it requires a
  // new Event to prevent unexpected triggering of a method (and possibly
  // infinite recursion) when the event type matches the method name
  trigger: function (type, data) {
    var event = new jQuery.Event(type); 
    event.preventDefault();                
    jQuery.event.trigger(event, data, this);
    return this;
  }
};

// Augment the object with jQuery's event methods
jQuery.each(['bind', 'one', 'unbind', 'on', 'off'], function (i, method) {
  jQuery.eventable.prototype[method] = function (type, data, fn) {
    jQuery(this)[method](type, data, fn);
    return this;
  };
});
var MODULE = function() {

  //  private
  var _field1;
  var _field2;

  function localFunc(p) {
    alert('localFunc');
  }

  //  public
  return $.eventable({

    // properties
    prop1: _field1,

    // public  methods
    method1: function(p) {
      alert('method1 says:' + p);
      this.trigger('myEvent1');
    },

    method2: function(p) {
      alert('method2 doing  stuff');
      localFunc(p);
      this.trigger('myEvent2');
    }

  });
} ();

// register for events
MODULE.on("myEvent1", function() {
  alert('fired1');
});
MODULE.on("myEvent2", function() {
  alert('fired2');
});

// use module (only event1 should fire!)
MODULE.method1("hello");
MODULE.on(event, /* data, */ handler);
MODULE.bind(event, /* data, */ handler);
MODULE.one(event, /* data ,*/ handler);
MODULE.off(event, handler);
MODULE.unbind(event, handler);
MODULE.trigger(event /*, data */);
Javascript module pattern issue

Javascript module pattern issue


By : marcusscarface
Date : March 29 2020, 07:55 AM
hope this fix your issue
The error I'm getting is that it doesn't recognize MF.foreach in function MFList.
code :
MF.prototype.foreach = ...
MF.foreach = ....
Slight variation of the Revealing Module Pattern

Slight variation of the Revealing Module Pattern


By : user2866812
Date : March 29 2020, 07:55 AM
wish of those help It's not the same. If you were to rename your module at any time or wish to use it in a different name, you won't be able to.
Also, by returning the object at the end of the array, you make it perfectly clear what's exposed out of the object.
Observer design pattern in Yii 1.1.16, attaching event handlers and rising events

Observer design pattern in Yii 1.1.16, attaching event handlers and rising events


By : user3480727
Date : March 29 2020, 07:55 AM
I wish this help you You don't need an observer class for your scenario.
Using Built in Event Handlers The Yii model class has a few built in functions that you can overwrite in your class.
code :
    /**
 * Runs just before the models save method is invoked. It provides a change to
 * ...further prepare the data for saving. The CActiveRecord (parent class)
 * ...beforeSave is called to process any raised events.
 *
 * @param <none> <none>
 * @return boolean the decision to continue the save or not.
 *
 * @access public
 */

public function beforeSave() {
    // /////////////////////////////////////////////////////////////////////
    // Some scenarios only require certain fields to be updated. We handle
    // ...this separately.
    // /////////////////////////////////////////////////////////////////////
if ($this->scenario == self::SCENARIO_LOGIN)
{
    /** Login scenario */
    $this->last_login = new CDbExpression('NOW()');
}

if ($this->scenario == self::SCENARIO_ACTIVATION)
{
    /** Account activation scenario */

    if ($this->activation_status == 'activated')
    {
        $this->activation_code = '';
        $this->status          = 'active';
        $this->activation_time = new CDbExpression('NOW()');
    }
}

if ( ($this->scenario == self::SCENARIO_CHANGE_PASSWORD) ||
     ($this->scenario == self::SCENARIO_REGISTER) ||
     ($this->scenario == 'insert') ||
     ($this->scenario == 'update')
   )
{
    /** Password change scenario */

    // /////////////////////////////////////////////////////////////////////
    // Encrypt the password. Only do this if the password is set
    // /////////////////////////////////////////////////////////////////////
    if (isset($this->password) && (!empty($this->password)))
    {
        $this->password    =  CPasswordHelper::hashPassword($this->password);

    }
}


/** All other scenarios */

// /////////////////////////////////////////////////////////////////////
// Set the create time and user for new records
// /////////////////////////////////////////////////////////////////////
if ($this->isNewRecord) {
    $this->created_time = new CDbExpression('NOW()');
    $this->created_by   = '1';  // Special case for not logged in user
    $this->modified_by  = '1';
}
else
{
    $this->modified_by   = isset(Yii::app()->user->id)?Yii::app()->user->id:1;
}

// /////////////////////////////////////////////////////////////////////
// The modified log details is set for record creation and update
// /////////////////////////////////////////////////////////////////////
$this->modified_time = new CDbExpression('NOW()');

return parent::beforeSave();
}
class NewUser extends CModelEvent{
    public $userRecord;
}
$userModel->attachEventHandler('onNewUser',newuserEventHandler);

function newuserEventHandler($event){
      // Add custom handling code here 
      do_some_things_here($event->new, $event->id);
    }
$event=new NewUserEvent;
// Add custom data to event.
$event->new=$this->isNewRecord;
$event->order=$this->id;
$this->raiseEvent('onNewUser',$event);
javascript module pattern context issue

javascript module pattern context issue


By : Steve Tang
Date : March 29 2020, 07:55 AM
I hope this helps . I am having trouble learning the module pattern, , implementation is sync, invocation is async
code :
this.getData = function(){
  return "data";
};

this.getData(function(err,data){
   alert(data);
});

//should be used either
var data = this.getData();
alert(data);

//or defined as

this.getData = function(callback){
  callback(null, "data");
};
return new Setup();

module.init();
return Setup;

var instance = new module();
instance.init();
Related Posts Related Posts :
  • I want to restrict HTML input autocomplete to 3 letter minimum
  • tinyMCE editor not updating on the fly
  • typescript kendo-ui call method from string
  • HttpCompileException was unhandled by user code (when i am adding c# code in script)
  • Send form data as array of objects to controller in asp.net mvc
  • Javascript, multi file modules and Require.Js
  • how to render a complete new template and leave the application template in ember
  • Hover unrelated divs
  • Permute string until it matches some input?
  • How to fire JQuery change event when input value changed programmatically?
  • AJAX: POST data to a different url
  • checkbox column in jquery datatable
  • Document.evaluate for documents without namespaceURI crashes Microsoft Edge
  • Bootstrap Menu with "More" option Responsive issue
  • Standard inputs not being added to Angularjs Form $Scope
  • Express promise throw error
  • onclick and get in jquery
  • How to get the country code from Google Places API
  • Passing parameters url in Select2
  • Is there any frame work for Marklogic to write javascript code?
  • How to implement a boostrap template over bootstrap-sass gem
  • Why fixed div comes out when horizontally scrolled?
  • How to limit scope of a function in javascript/ jquery
  • Overlapping legend d3.js
  • Apply transition to div
  • Javascript game help - counting with dice
  • How to hide a div from angular controller
  • Can Promise load multi urls in order?
  • How enable Hover event for bootstrap menus?
  • D3 scale.invert() isn't returning date for x
  • Parsing object to array using underscore js or lodash
  • ES6 with React and Browserify
  • AngularJS Factory return type undefined
  • javascript follow html input fields
  • how to declare a double array in javascript for this particular UI
  • Jquery : find length of mixed list
  • Returning the array before the function is complete & Angular JS
  • Javascript set value of class & hidden input in nested divs
  • Register custom filters with vue.js
  • Add class to input parent
  • Angular controller not talking to view
  • Trouble creating "if then" Javascript statement to change background color of page
  • Socket.IO - Middleware and scoping: how should I access global IO object from external middleware?
  • add class when input is valid in angularjs
  • Positioning multiple div elements
  • Checkbox clicking works, deselecting checkbox not working Javascript
  • Adding ajax jQuery File upload
  • Creating a dynamic array within a dynamic array in JQuery
  • Multiple File Upload actions for a single File Input PHP/JS
  • Want to move an added element to a different part of the DOM
  • Why can't I get Angularjs to work?
  • Minimizing browser window in Firefox & Chrome adds white space to right of page
  • I need to insert the date and time of employee stamp in and out into mysql database
  • Making css auto slider
  • why can't I defne the function first?
  • Pagination with MongoDB in Node.js (With Sorting)
  • How to repeat each() without page refresh
  • Position div at position of another div
  • Click handler is called multiple times in jQuery animate
  • How to multiply each element in an array with a different number (javascript)
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co