Giter Club home page Giter Club logo

onmount's Introduction

onmount

Run something when a DOM element appears and when it exits.
No dependencies. Legacy IE compatible. 1kb .min.gz.

Overview

Detecting elements

Run something to initialize an element on its first appearance.

onmount = require('onmount')

onmount('.push-button', function() {
  $(this).on('click', function() {
    alert('working...')
  })
})

See: Premise

Using with React

🎉 If you're looking to use Onmount to mount React components, check out Remount instead.

Polling for changes

Call $.onmount() everytime your code changes.

$('<button class="push-button">Do something</button>').appendTo('body')

$.onmount()

$('.push-button').click() //=> 'working...'

See: Idempotency

jQuery integration

jQuery is optional; use it to poll on popular events.

$(document).on('ready show.bs closed.bs load page:change', function() {
  $.onmount()
})

See: API

Cleanups

Supply a 2nd function to onmount() to execute something when the node is first detached.

$.onmount(
  '.push-button',
  function() {
    /*...*/
  },
  function() {
    alert('button was removed')
  }
)

document.body.innerHTML = ''

$.onmount() //=> 'button was removed'

See: Cleanups

What for?

Onmount is a safe, reliable, idempotent, and testable way to attach JavaScript behaviors to DOM nodes. It's great for common websites that are not Single-Page Apps. Read more on its premise and motivation.

rsjs (Reasonable System for JavaScript Structure) is a great standard that onmount fits perfectly into.

Usage

Onmount is available via npm and Bower.

npm install onmount
bower install onmount

It can be used as a CommonJS module or on its own. It doesn't require jQuery, but if jQuery is found, it'll attach itself to it as $.onmount.

onmount = require('onmount') // With CommonJS (ie, Browserify)
window.onmount // with no module loaders:
$.onmount // with jQuery

API

See: API

Browser compatibility

All modern browsers and IE8+. For legacy IE, use it with jQuery 1.x.

Examples

Examples are available in the source repo. See examples →

Thanks

onmount © 2015+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors (list).

ricostacruz.com  ·  GitHub @rstacruz  ·  Twitter @rstacruz

onmount's People

Contributors

dependabot[bot] avatar greenkeeperio-bot avatar padi avatar rstacruz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

onmount's Issues

Please add way to instrument the methods invoked by onmount

I'd like to wrap the functions invoked by onmount on enter/exit, in order to integrate my error reporting service (I'd like to describe the affected element in the error report).

Right now I'm using a very ugly hack to be able to wrap Behavior.prototype.visitEnter, but a supported way would be better.

Double initialization when using using browser back

I am using onmount along with TL5.
When I navigate to a page via turbolinks, press browser back and then forward, onmount is initialized again.

Changing visitEnter to below solved the issue for me.

Behavior.prototype.visitEnter = function (el) {
    if (el[this.key] || el.getAttribute("__onmount")) return
    el.setAttribute("__onmount", this.key);
    var options = { id: 'c' + cid, selector: this.selector }

All state in Behaviour seems to be lost when navigating via browser back - but the html attributes seem to be intact - so I added a html attribute based guard also.

Would you mind letting me know if there could be some configuration issue in my setup or this is a known issue?

EDIT: I am facing some other issues with above code.

Strange issue - onmount doesn't work

Hi there,

First of all, thanks for your useful JS guide. I wanted to ask for your advice - for some reason, onmount doesn't work for me (maybe I'm missing something obvious). Here's the HTML page:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Testing onmount</title>
  <meta name="description" content="Testing onmount">
  <meta name="author" content="Sergey Monin">

</head>

<body>
  <div class="test">Test element</div>
  <script src="bundle.js"></script>
</body>
</html>

Here's the js file:

import onmount from 'onmount'

onmount('.test', function () {
    console.log('test passed');
    // Silence... nothing in console (in both Firefox / Chrome).
})

And... nothing.

I tried everything:

  1. Used var onmount = require('onmount') instead of import.
  2. Tried to import jQuery and then used $.onmount.
  3. Tried to replace class with data-attribute data-js-test as recommended in your guide.
  4. Tried to load onmount.js as independent script and then used window.onmount();

Here's the generated bundle.js. And here's my gulp task:

// Compile scripts
gulp.task('scripts-compile', function () {
  const b = browserify({
    entries: 'app.js',
    transform: babelify,
    debug: true
  });

  return b.bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(gulp.dest(config.dest))
});

Package.json config:

"browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "@babel/preset-env"
          ]
        }
      ]
    ]
  }

Eslintrc.json

{
  "parserOptions": {
    "ecmaVersion": 2018,
    "ecmaFeatures": {
      "jsx": true
    },
    "sourceType": "module"
  },

  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true,
    "jquery": true
  },

  "plugins": [
    "import",
    "node",
    "promise",
    "standard"
  ],

  "globals": {
    "document": false,
    "navigator": false,
    "window": false
  }
}

Any idea of how to make it work?

Error when importing

I’m running into an error when importing onmount using ES6 import statements alongside Jquery

import $ from 'jquery';
import onmount from 'onmount';

As the documentation mentions It doesn't require jQuery, but if jQuery is found, it'll attach itself to it as $.onmount

But i still get the following error when using $.onmount jquery__WEBPACK_IMPORTED_MODULE_0___default.a.onmount is not a function.

Any help would be appreciated.

Issue with back button and turbolinks 5

Everything seems to work fine except when hitting the back button after a Turbolink visit
Consider this code:

import $ from 'jquery'
import SimpleMDE from 'simplemde';

$.onmount('#markitup', function () {
  if ($("#markitup").length === 1) {
    var simplemde = new SimpleMDE({ element: $("#markitup")[0] });
  }
})

$(document).on('ready turbolinks:load', function () { $.onmount() })
$(document).on('turbolinks:before-render', function () { $.onmount.teardown() })

SimpleMDE is never triggered twice while changing the page (clicking on links) except when pressing the back button

$.onmount is not a function (must be missing something)

I must be missing something completely (since I cannot read your fine instructions by the letter) in my

$ bundle exec rails server
=> Booting Puma
=> Rails 5.2.0 application starting in development
=> Run `rails server -h` for more startup options
audited 1 package in 1.347s
found 0 vulnerabilities

Puma starting in single mode...
* Version 3.11.4 (ruby 2.5.1-p57), codename: Love Song
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

First I did npm install onmount and made sure it made it into the package.json

{
  "name": "arkivthy",
  "private": true,
  "dependencies": {
    "onmount": "^1.3.0"
  }
}

then I required it in app/assets/javascripts/application.js

//= require onmount

further I prepped the bottom of my app/views/layouts/application.html.haml

    %script{ :src=>"https://code.jquery.com/jquery-3.2.1.slim.min.js", :integrity=>"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN", :crossorigin=>"anonymous"}
    %script{ :src=>"https://unpkg.com/[email protected]/dist/umd/popper.js", :integrity=>"sha384-fA23ZRQ3G/J53mElWqVJEGJzU0sTs+SvzG8fXVWP+kJQ1lwFAOkcUOysnlKJC33U", :crossorigin=>"anonymous"}
    %script{ :src=>"https://unpkg.com/[email protected]/dist/js/bootstrap-material-design.js", :integrity=>"sha384-CauSuKpEqAFajSpkdjv3z9t8E7RlpJ1UP0lKM/+NdtSarroVKu069AlsRPKkFBz9", :crossorigin=>"anonymous"}

  :coffeescript

    $(document).on "turbolinks:load", ->
      $.onmount()
      $('body').bootstrapMaterialDesign()
      window.addEventListener "turbolinks:load", Pagy.init

    $('<button class="push-button">Do something</button>').appendTo('body')
    $.onmount()
    $(".push-button").click()

'cause I get this every time:

Uncaught TypeError: $.onmount is not a function
    at avisudklips:1661
    at avisudklips:1665
(anonymous) @ avisudklips:1661
(anonymous) @ avisudklips:1665
Uncaught TypeError: $.onmount is not a function
    at HTMLDocument.<anonymous> (avisudklips:1654)
    at HTMLDocument.dispatch (jquery-3.2.1.slim.min.js:3)
    at HTMLDocument.q.handle (jquery-3.2.1.slim.min.js:3)
    at Object.Turbolinks.dispatch (turbolinks.self-2db6ec539b9190f75e1d477b305df53d12904d5cafdd47c7ffd91ba25cbec128.js?body=1:6)
    at e.notifyApplicationAfterPageLoad (turbolinks.self-2db6ec539b9190f75e1d477b305df53d12904d5cafdd47c7ffd91ba25cbec128.js?body=1:7)
    at e.pageLoaded (turbolinks.self-2db6ec539b9190f75e1d477b305df53d12904d5cafdd47c7ffd91ba25cbec128.js?body=1:7)
    at turbolinks.self-2db6ec539b9190f75e1d477b305df53d12904d5cafdd47c7ffd91ba25cbec128.js?body=1:6

while at the same time

window.onmount()
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
$('#arkivEdit')
r.fn.init [div#arkivEdit.modal.fade]

looks to me like window knows of the onmount - what the heck is eluding me?

init function not ran on already existing nodes matching the selector

Hello,

With my current setting, onmount() is called when the document DOMContentLoaded is fired. At this point the DOM node I am interested in is already present in the page but if I call onmount('[data-js-behavior-name]', function init() {...}) then the init function is not called until the next onmount() or onmount('[data-js-behavior-name]') call. Would it not make sense for onmount(selector, init) to call init on each of the selector matching DOM elements and not wait for the next polling call?

Doesn't work with latest turbolinks

I have tried to use TL5 (which is most likely going to be bundled with rails 5) with onmount but it doesn't seem to auto-initialize components.
One of the difference I found is that the DOM elements from cached pages are still accessible on any page.

I added the initializer as described in rails doc

P.S.: You may already be aware of it, after all its you(rstacruz) who initiated the discussion. I want to know if there are any plans to support it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.